package com.yangaobo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yangaobo.dto.SchoolInsertDTO;
import com.yangaobo.dto.SchoolPageDTO;
import com.yangaobo.dto.SchoolUpdateDTO;
import com.yangaobo.entity.School;
import com.yangaobo.excel.SchoolExcel;
import com.yangaobo.exception.ServerErrorException;
import com.yangaobo.mapper.SchoolMapper;
import com.yangaobo.service.SchoolService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 杨奥博
 */
@Service
@CacheConfig(cacheNames = "school")
public class SchoolServiceImpl implements SchoolService {

    @Resource
    private SchoolMapper schoolMapper;

    @CacheEvict(allEntries = true)
    @Override
    public int insert(SchoolInsertDTO dto) {
        School school = BeanUtil.copyProperties(dto, School.class);

        if(StrUtil.isBlank(dto.getInfo())) {
            school.setInfo("暂无描述");
        }
        school.setDeleted(0);
        school.setVersion(0L);
        school.setCreated(LocalDateTime.now());
        school.setUpdated(LocalDateTime.now());
        int result = schoolMapper.insert(school);
        if (result <= 0) {
            throw new ServerErrorException("DB添加失败");
        }
        return result;
    }

    // 缓存key为id，缓存条件为id不为空，缓存unless为结果为空
    @Cacheable(key = "#p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public School select(Long id) {
        School result = schoolMapper.select(id);
        if (ObjectUtil.isNull(result)) {
            throw new ServerErrorException("DB查询失败");
        }
        return result;
    }

    // 缓存key为方法名（list），缓存条件为结果不为空
    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<School> list() {
        return schoolMapper.list(new SchoolPageDTO())
                .stream()
                .map(school -> BeanUtil.copyProperties(school, School.class))
                .collect(Collectors.toList());
    }

    // 方法名:pageNum:pageSize; dto!=null走缓存; 若查出结果为null不存缓存
    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
            condition = "#p0 != null",
            unless = "#result == null")
    @Override
    public PageInfo<School> page(SchoolPageDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return new PageInfo<>(schoolMapper.list(dto));
    }

    // Transactional 若抛出异常自动回滚事务；
    // Retryable 方法抛出 VersionException 时，自动重试执行（默认重试 3 次）
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(SchoolUpdateDTO dto) {
        School school = schoolMapper.select(dto.getId());
        if(ObjectUtil.isNull(school)) {
            throw new ServerErrorException("DB查询失败");
        }
        // Hutool 的 BeanUtil 支持拷贝时忽略空值
        BeanUtil.copyProperties(dto, school,
                CopyOptions.create().setIgnoreNullValue(true));
        school.setUpdated(LocalDateTime.now());
        int result = schoolMapper.update(school);
        if(result <= 0) {
            throw new ServerErrorException("DB修改失败");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int delete(Long id) {
        int result = schoolMapper.delete(id);
        if(result <= 0) {
            throw new ServerErrorException("DB删除失败");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int deleteBatch(List<Long> ids) {
        int result = schoolMapper.deleteBatch(ids);
        if(result <= 0) {
            throw new ServerErrorException("DB删除失败");
        }
        return result;
    }

    @Override
    public List<SchoolExcel> getExcelData() {
        return schoolMapper.list(new SchoolPageDTO())
                .stream()
                .map(school -> BeanUtil.copyProperties(school, SchoolExcel.class))
                .collect(Collectors.toList());
    }

}
